import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch,Popconfirm,Pagination,DatePicker,Spin} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import SearchPanel from '../common/SearchPanel';
import RemarkModal from '../common/RemarkModal';
import DataAnalyzeTable from '../common/DataAnalyzeTable';

import {ANALYZE_TABLE_TYPE} from '../constants/index';
import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';
const {RangePicker} = DatePicker


export default class PropertyDataList extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           // page:0,
           // total:1,
           // pageSize:10,
           list:[],
           loading:false,
           data:{
            assetPoolData:{},//资产池
            topFive:[],//top5
            paymentDaysAnalyze:[],//账期分析
            concentrateAnalyze:{},//集中度分析
            areaAnalyze:{},//地域分析
            debtorAnalyze:[],//债务人分析
            goodsAnalyze:[],//货物分析
            assetAnalyze:[],
           },
           concentratePagination:{
            page:1,
            pageSize:10,
            total:1,
           },
           areaPagination:{
            page:1,
            pageSize:10,
            total:1,
           },
           paymentDaySubType:1,//账期子类型
           concentrateSubType:1,//集中度子类型
           areaSubType:1,//地域子类型
           debtorSubType:1,//债务子类型
           goodsSubType:1,//货物分析
           assetAnalyzeSubType:1,//资产分析
           period:3,
           session:{},
           periods:[],


        };
    }

     componentWillMount(){
      // let {page,pageSize} = this.state
      this.setState({
        loading:true,
      })
      let{period} = this.state;
      this.doFetch(period);
    }
     componentWillReceiveProps(nextProps){
        //  let session = await this.props.route.session();
        // this.setState({
        //   session
        // })
    }
    //查询列表
    async doFetch(period){
      let session =  this.props.route.session;
      let {data, concentratePagination, areaPagination} = this.state;
      let result = await api("/property/propertyData/getAll",{period});
      if (result.assetPoolData.success) {
        data.assetPoolData = result.assetPoolData.data;
      }else{
        message.error(result.assetPoolData.message)
      }
      if (result.topFive.success) {
        data.topFive = result.topFive.data;
      }else{
        message.error(result.topFive.message)
      }
      if (result.paymentDaysAnalyze.success) {
        data.paymentDaysAnalyze = result.paymentDaysAnalyze.data;
      }else{
        message.error(result.paymentDaysAnalyze.message)
      }
      if (result.concentrateAnalyze.success) {
        data.concentrateAnalyze = result.concentrateAnalyze.data;
        concentratePagination.page = result.concentrateAnalyze.data.pageNumber;
        concentratePagination.pageSize = result.concentrateAnalyze.data.pageSize;
        concentratePagination.total = result.concentrateAnalyze.data.totalItem;

      }else{
        message.error(result.concentrateAnalyze.message)
      }
      if (result.areaAnalyze.success) {
        data.areaAnalyze = result.areaAnalyze.data;
        areaPagination.page = result.areaAnalyze.data.pageNumber;
        areaPagination.pageSize = result.areaAnalyze.data.pageSize;
        areaPagination.total = result.areaAnalyze.data.totalItem;
      }else{
        message.error(result.areaAnalyze.message)
      }
      if (result.debtorAnalyze.success) {
        data.debtorAnalyze = result.debtorAnalyze.data;
      }else{
        message.error(result.debtorAnalyze.message);
      }
      if (result.goodsAnalyze.success) {
        data.goodsAnalyze = result.goodsAnalyze.data;
      }else{
        message.error(result.goodsAnalyze.message)
      }

      if (result.assetAnalyze.success) {
        data.assetAnalyze = result.assetAnalyze.data;
      }else{
        message.error(result.assetAnalyze.message);
      }

      this.setState({
        data,
        loading:false,
        concentratePagination,
        areaPagination,
        period,
        session
      })
    }

    //获取期数
    async getAssetsPeriods(){
      let result = await api("/property/getAssetsPeriods",{});
      console.log('test',result);
      if (result.success) {
        this.setState({
          periods:result.data
        })
      }
      
    }

    formatNumber(num) {
      return (num / 10000).toFixed(2).toString();
    }

    toMoneyFormat(number){
       let s = this.formatNumber(number);
        if(/[^0-9\.]/.test(s)) return "invalid value";
        s=s.replace(/^(\d*)$/,"$1.");
        s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
        s=s.replace(".",",");
        var re=/(\d)(\d{3},)/;
        while(re.test(s))
            s=s.replace(re,"$1,$2");
        s=s.replace(/,(\d\d)$/,".$1");
        return s.replace(/^\./,"0.")
    }


    onChangeType(type,value){
      switch(type) {
        case ANALYZE_TABLE_TYPE[0]:
          this.getPaymentDaysAnalyze(value);
          break;
        case ANALYZE_TABLE_TYPE[1]:
          this.getConcentrateAnalyze(value);
          break;
        case ANALYZE_TABLE_TYPE[2]:
          this.getAreaAnalysis(value);
        
          break;
        case ANALYZE_TABLE_TYPE[3]:
          this.getBuyerAnalysis(value);
          
          break;
        case ANALYZE_TABLE_TYPE[4]:
          this.getGoodsAnalysis(value);
          
          break;
        case ANALYZE_TABLE_TYPE[5]:
          this.getAssetAnalyze(value);
          break;
      }
    }

    //根据type获取账期分析
    async getPaymentDaysAnalyze(type){
      let {data,period} = this.state;
      let result = await api('/property/getBillAnalysis/list',{type,period});

      if (result.success) {
        data.paymentDaysAnalyze = result.data;
        this.setState({
          data,
          paymentDaySubType:type,
        })
      }else{
        message.error(result.message);
      }
    }

    //根据type获取集中度分析
    async getConcentrateAnalyze(type,pageNumber,pageSize){
      let {data,concentratePagination,period} = this.state;
      let result = await api('/property/getConcentrationAnalysis/list',{type:type,pageNumber:pageNumber || 1,pageSize:pageSize||10,period:period});

      if (result.success) {
        data.concentrateAnalyze = result.data;
        concentratePagination.page = pageNumber,
        concentratePagination.pageSize = pageSize,
        concentratePagination.total = result.data.totalItem,
        this.setState({
          data,
          concentrateSubType:type,
          concentratePagination
        })
      }else{
        message.error(result.message);
      }
    }

    //根据type获取地域分析
    async getAreaAnalysis(type,pageNumber,pageSize){
      let {data,areaPagination,period} = this.state;

      let result = await api('/property/getAreaAnalysis/list',{type:type,pageNumber:pageNumber || 1,pageSize:pageSize || 10,period:period});

      if (result.success) {
        data.areaAnalyze = result.data;
        areaPagination.page = pageNumber,
        areaPagination.pageSize = pageSize,
        areaPagination.total = result.data.totalItem,
        this.setState({
          data,
          areaSubType:type,
          areaPagination
        })
      }else{
        message.error(result.message);
      }
    }

    //根据type获取债务人分析
    async getBuyerAnalysis(type){
      let {data,period} = this.state;
      let result = await api('/property/getBuyerAnalysis/list',{type,period});

      if (result.success) {
        data.debtorAnalyze = result.data;
        this.setState({
          data,
          debtorSubType:type,
        })
      }else{
        message.error(result.message);
      }
    }

    //根据type获取货物分析
    async getGoodsAnalysis(type){
      let {data,period} = this.state;
      let result = await api('/property/getGoodsAnalysis/list',{type,period});

      if (result.success) {
        data.goodsAnalyze = result.data;
        this.setState({
          data,
          goodsSubType:type
        })
      }else{
        message.error(result.message);
      }
    }

    //根据type获取资产分析
    async getAssetAnalyze(type){
      let {data,period} = this.state;
      let result = await api('/property/getAssetAnalysis/list',{type,period});

      if (result.success) {
        data.assetAnalyze = result.data;
        this.setState({
          data,
          assetAnalyzeSubType:type,
        })
      }else{
        message.error(result.message);
      }
    }

    //分页
    onPageChange(type,page,pageSize,total){
      if (type == ANALYZE_TABLE_TYPE[1]) {
        let {concentrateSubType} = this.state;
        this.getConcentrateAnalyze(concentrateSubType,page,pageSize)
      }else if (type == ANALYZE_TABLE_TYPE[2]) {
        let {areaSubType} = this.state;
        this.getAreaAnalysis(areaSubType,page,pageSize);
      }
    }

    onChangePeriod(value){
      this.setState({
        period:value,
        loading:true,
      })
      this.doFetch(value);
    }

    
    
    render() {

        var {list,paymentDaySubType,concentrateSubType,areaSubType,debtorSubType,goodsSubType,assetAnalyzeSubType,concentratePagination,areaPagination}=this.state;
        let {assetPoolData,//资产池
            topFive,//top5
            paymentDaysAnalyze,//账期分析
            concentrateAnalyze,//集中度分析
            areaAnalyze,//地域分析
            debtorAnalyze,//债务人分析
            goodsAnalyze,//货物
            assetAnalyze,//资产分析
          }=this.state.data
        return (
            <Spin spinning={this.state.loading}>
            <div className="bgWhite marginL25 marginB40">
                <div style={{"padding":"20px","background":"#F7F7F7"}}>
                    <div className="containerWithBorder paddingT15 bgWhite">
                        <div className="marginL15 marginR15">
                            <div style={{"float":"left",marginTop:"10px"}}>资产池数据</div>
                            <div className="text-right">
                                <Select 
                                  onChange={this.onChangePeriod.bind(this)}
                                  style={{width:230}}
                                  defaultValue="3"
                                >
                                  <Option key="3" value="3">第3期（2018-09-01 至 2018-11-30）</Option>
                                  <Option key="2" value="2">第2期（2018-06-01 至 2018-08-31）</Option>
                                  <Option key="1" value="1">第1期（2018-03-01 至 2018-05-31）</Option>
                                </Select>
                                <Button
                                  className='marginL10'
                                >导出<Icon type="download" /></Button>
                            </div>
                        </div>

                        <Row className="marginT20">
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                
                            >
                                <div className="marginL15">
                                    <p>存续合同数</p>
                                    <p style={{fontSize:24}}>{assetPoolData.existenceContract || "0"}<span style={{fontSize:12}}>个</span></p>
                                    <p>债务人{assetPoolData.buyer || "0"}个</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>基础资产笔数</p>
                                    <p style={{fontSize:24}}>{assetPoolData.countBaseAsset || "0"}<span style={{fontSize:12}}>笔</span></p>
                                    <p>每债务人平均{assetPoolData.averageAsset || "0"}笔</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>应收账款总金额</p>
                                    <p style={{fontSize:24}}>{
                                      assetPoolData.sumAssetMoney?
                                      this.toMoneyFormat(assetPoolData.sumAssetMoney)
                                      :
                                      "0.00"
                                    }<span style={{fontSize:12}}>万元</span></p>
                                    <p>单笔平均{
                                      assetPoolData.aveAssetMoney?
                                      this.toMoneyFormat(assetPoolData.aveAssetMoney)
                                      :"0.00"
                                    }万元</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>应收账款余额</p>
                                    <p style={{fontSize:24}}>{
                                      assetPoolData.sumAssetAvailableMoney?
                                      this.toMoneyFormat(assetPoolData.sumAssetAvailableMoney)
                                      :"0.00"
                                    }<span style={{fontSize:12}}>万元</span></p>
                                    <p>单笔平均{
                                      assetPoolData.aveAssetAvailableMoney?
                                      this.toMoneyFormat(assetPoolData.aveAssetAvailableMoney)
                                      :"0.00"
                                    }万元</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>逾期资产金额</p>
                                    <p style={{fontSize:24}}>{
                                      assetPoolData.sumOverdueAssetMoney?
                                      this.toMoneyFormat(assetPoolData.sumOverdueAssetMoney)
                                      :"0.00"
                                    }<span style={{fontSize:12}}>万元</span></p>
                                    <p>逾期比例{assetPoolData.overdueRate || "0"}%</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>闲置资金金额</p>
                                    <p style={{fontSize:24}}>{
                                      assetPoolData.sumUnusedAssetMoney?
                                      this.toMoneyFormat(assetPoolData.sumUnusedAssetMoney)
                                      :"0.00"
                                    }<span style={{fontSize:12}}>万元</span></p>
                                    <p>闲置比例{assetPoolData.unusedRate || "0"}%</p>
                                </div>
                            </Col>
                        </Row>
                    </div>

                    <Table
                        columns={this.getTop5Columns()}
                        dataSource={topFive}
                        title={() => {
                                return (<div className="marginL15">资产TOP5</div>)
                            }
                        }
                        className="containerWithTopBorder containerWithRightAndLeftBorder marginT20 bgWhite"
                        pagination={false}
                        rowKey={(record,index) => index}
                    >
                    </Table>
                    {/*账期分析*/}
                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[0]}
                        list={paymentDaysAnalyze}
                        subType={paymentDaySubType}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[0])}
                    />
                    {/*集中度分析*/}
                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[1]}
                        list={
                            concentrateAnalyze && concentrateAnalyze.pageResult ?
                              concentrateAnalyze.pageResult
                            :
                              []
                            }
                        subType={concentrateSubType}
                        pagination={concentratePagination}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[1])}
                        onPageChange={this.onPageChange.bind(this,ANALYZE_TABLE_TYPE[1])}
                    />
                  {/*地域分析*/}
                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[2]}
                        list={
                          areaAnalyze && areaAnalyze.pageResult ?
                              areaAnalyze.pageResult
                            :
                              []
                        }
                        
                        subType={areaSubType}
                        pagination={areaPagination}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[2])}
                        onPageChange={this.onPageChange.bind(this,ANALYZE_TABLE_TYPE[2])}
                    />
                  {/*债务人分析*/}
                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[3]}
                        list={debtorAnalyze}
                        subType={debtorSubType}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[3])}
                    />
                  {/*货物分析*/}
                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[4]}
                        list={goodsAnalyze}
                        subType={goodsSubType}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[4])}
                    />
                  {/*资产分析*/}
                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[5]}
                        list={assetAnalyze}
                        subType={assetAnalyzeSubType}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[5])}
                    />
                </div>
            </div>
            </Spin>
               
        );
    }

    getTop5Columns(){
      let {session} = this.state;
      let columns = [
            {
              title: '资产编号',
              dataIndex: 'number',
              key: 'number',
            }, {
              title: '应收总金额',
              dataIndex: 'money_sum',
              key: 'money_sum',
            }, {
              title: '应收余额',
              dataIndex: 'available_money',
              key: 'available_money',
            },{
              title: '应收账期',
              dataIndex: 'credit_day',
              key: 'credit_day',
            }, {
              title: '剩余期限',
              dataIndex: 'remain_days',
              key: 'remain_days',
            }
        ];

        return columns
    }

    
}

PropertyDataList.contextTypes= { router: React.PropTypes.object.isRequired};
